import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import { Button, DatePicker, Drawer, message, Space, Tooltip } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateModal from './components/UpdateForm';
import CreateModal from './components/CreateForm';
import {
  addInterfaceInfoUsingPost,
  deleteInterfaceInfoUsingPost,
  listInterfaceInfoByPageUsingGet,
  offlineInterfaceInfoUsingPost,
  onlineInterfaceInfoUsingPost,
  updateInterfaceInfoUsingPost,
} from '@/services/api-share-backhend/interfaceInfoController';
import { SortOrder } from 'antd/lib/table/interface';
import moment from 'moment';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(true);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>();
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfo[]>([]);
  const handleAdd = async (fields: API.InterfaceInfoAddRequest) => {
    const hide = message.loading('正在添加');
    try {
      const res = await addInterfaceInfoUsingPost({
        ...fields,
      });
      hide();
      if (res.data) {
        if (actionRef.current) {
          actionRef.current.reload();
        }
        message.success('添加成功');
      } else {
        message.error(res.message);
      }
      return true;
    } catch (error) {
      hide();
      message.error('添加失败');
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfoUpdateRequest) => {
    const hide = message.loading('正在修改');
    try {
      const res = await updateInterfaceInfoUsingPost({
        ...fields,
      });
      hide();
      if (res.data) {
        message.success('修改成功');
      } else {
        message.error(res.message);
      }

      return true;
    } catch (error) {
      hide();
      message.error('修改失败');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.InterfaceInfo[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const ids: API.IdRequest[] = selectedRows.map((item) => {
        return { id: item.id };
      });
      const res = await deleteInterfaceInfoUsingPost(ids);
      hide();

      if (res.data) {
        if (actionRef.current) {
          actionRef.current.reload();
        }
        message.success('删除成功');
      } else {
        message.error(res.message);
      }
      return true;
    } catch (error) {
      hide();
      message.error('删除失败');
      return false;
    }
  };

  /**
   * 接口上下线
   * @author maktoub
   *
   */
  const handleChangeStatus = async (selectedRows: API.InterfaceInfo) => {
    const hide = message.loading('操作中……');
    if (!selectedRows) return true;
    try {
      const idReq: API.IdRequest = {
        id: selectedRows.id,
      };
      hide();
      let res;
      if (selectedRows.status === 0) {
        res = await onlineInterfaceInfoUsingPost(idReq);
      } else {
        res = await offlineInterfaceInfoUsingPost(idReq);
      }
      if (res.data) {
        if (actionRef.current) {
          actionRef.current.reload();
        }
        if (selectedRows.status === 0) {
          message.success('上线成功');
        } else {
          message.success('下线成功');
        }
      } else {
        message.error(res.message);
      }
      return true;
    } catch (error) {
      hide();
      message.error('服务器出错');
      return false;
    }
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      width: 50,
      valueType: 'index',
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      width: 90,
      valueType: 'text',
      ellipsis: true,
      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.name}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
      formItemProps: {
        rules: [
          {
            required: true,
          },
          {
            max: 30,
            message: '接口名称过长',
          },
        ],
      },
    },
    {
      title: '接口描述',
      width: 120,
      dataIndex: 'description',
      valueType: 'textarea',

      ellipsis: true,
      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.description}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
      formItemProps: {
        rules: [
          {
            required: true,
          },
          {
            max: 120,
            message: '接口描述过长',
          },
        ],
      },
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      width: 50,

      valueEnum: {
        GET: {
          text: 'GET',
          // status: 'Default',
        },
        PUT: {
          text: 'PUT',
          // status: 'Default',
        },
        DELETE: {
          text: 'DELETE',
          // status: 'Default',
        },
        POST: {
          text: 'POST',
          // status: 'Processing',
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',

      onCell: () => {
        return {
          style: {
            maxWidth: 200,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },

      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.requestHeader}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),

      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],

      },
      fieldProps: {
        placeholder: `{"key":"value"}`,
      },
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
      onCell: () => {
        return {
          style: {
            maxWidth: 200,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },

      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.responseHeader}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],

      },
      fieldProps: {
        placeholder: `{"key":"value"}`,
      },
    },
    {
      title: '请求参数',
      dataIndex: 'requestParams',
      valueType: 'jsonCode',

      onCell: () => {
        return {
          style: {
            maxWidth: 200,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },

      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.requestParams}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),

      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
      fieldProps: {
        placeholder: `[{"param":"参数名","type":"类型"}]`,
      },
    },
    {
      title: '接口地址',
      dataIndex: 'url',
      valueType: 'text',
      width: 200,
      ellipsis: true,

      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.url}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '接口状态',
      dataIndex: 'status',
      hideInForm: true,
      width: 50,
      valueEnum: {
        0: {
          text: '已关闭',
          status: 'Default',
        },
        1: {
          text: '已开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <DatePicker
            {...rest}
            needConfirm={true}
            onOk={(value) => form.setFieldsValue({ createTime: value })}
          />
        );
      },
      width: 90,
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      width: 90,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <DatePicker
            {...rest}
            needConfirm={true}
            onOk={(value) => form.setFieldsValue({ updateTime: value })}
          />
        );
      },
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: 90,
      valueType: 'option',
      render: (_, record) => (
        <Space direction="vertical">
          <Button
            key={'change'}
            onClick={() => {
              handleUpdateModalOpen(true);
              setCurrentRow(record);
            }}
          >
            修改
          </Button>
          {record.status === 0 ? (
            <Button
              key={'online'}
              style={{ color: '#1677FF' }}
              onClick={() => {
                handleChangeStatus(record);
              }}
            >
              上线
            </Button>
          ) : null}
          {record.status === 1 ? (
            <Button
              key={'offline'}
              style={{ color: '#F7B179' }}
              onClick={() => {
                handleChangeStatus(record);
              }}
            >
              下线
            </Button>
          ) : null}
          <Button
            key={'delete'}
            style={{ color: 'red' }}
            onClick={() => {
              handleRemove([record]);
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];


  return (
    <PageContainer>
      <ProTable<API.InterfaceInfo, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        loading={loading}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={
          async (
            params,
            sort: Record<string, SortOrder>,
            filter: Record<string, (string | number)[] | null>,
          ) => {
            setLoading(true)
            const res = await listInterfaceInfoByPageUsingGet({ ...params });
            if (res?.data) {
              const ans = {
                data: res.data.records,
                success: true,
                total: res.data.total,
              };
              setLoading(false)
              return ans;
            } else {
              const ans = {
                data: null,
                success: false,
                total: res.data.total,
              };
              setLoading(false)
              return ans;
            }
          } //请求数据
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                {/*服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万*/}
              </span>
            </div>
          }
        >
          <Button
            type="primary"
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <UpdateModal
        onSubmit={async (value: API.InterfaceInfo) => {
          value.id = currentRow?.id;
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={updateModalOpen}
        currentRow={currentRow || {}}
        columns={columns}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.InterfaceInfo>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.InterfaceInfo>[]}
          />
        )}
      </Drawer>

      <CreateModal
        columns={columns}
        createModalOpen={createModalOpen}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSubmit={(values) => {
          const res = handleAdd(values);
          if (res === true) {
            handleModalOpen(false);
          }
        }}
      ></CreateModal>
    </PageContainer>
  );
};
export default TableList;
